package com.itmk.annotation;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.itmk.context.UserContext;
import com.itmk.context.UserContextInfo;
import com.itmk.jwt.JwtUtils;
import com.itmk.web.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 山顶洞人郑某
 * @className 拦截器 jwt令牌技术拦截
 * @date 2023 12 15
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse
            response, Object handler) throws Exception {
        Auth annotation;
        if(handler instanceof HandlerMethod){
            annotation = ((HandlerMethod)
                    handler).getMethodAnnotation(Auth.class);
        }else{
            return true;
        }
        if(annotation == null){
            return true;
        }
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            token = request.getParameter("token");
        }
        if(StringUtils.isEmpty(token)){
            throw new BusinessException(600,"token不能为空!");
        }
        boolean expired = jwtUtils.verify(token);
        if(!expired){
            throw new BusinessException(600,"token验证失败!");
        }

        return true;
    }

}
